/**
 * 主页
 *
 */
import Layout from "@/components/layout";
import Banner from "./components/Banner";
import AnimatingNumbers from "./components/AnimatingNumbers";
import NoticeBar from "./components/NoticeBar";
import CardList from "./components/CardList";
import { useRequest } from "taro-hooks";
import {
  ApiGetPageData,
  bindUser,
  decryptPhoneNumber,
  getOpenIdList,
  IBindUserParams,
  IDecryptPhoneNumberParams,
  setCookie,
} from "./api";
import Skeleton from "./skeleton-loading";
import Taro, { getCurrentInstance, useLoad } from "@tarojs/taro";
import { useEffect, useRef, useState } from "react";
import { Avatar, Button, Dialog } from "@nutui/nutui-react-taro";
import { instance as Log } from "@/lib/log";
import { View, Text, Image, Input } from "@tarojs/components";
import jump from "@/lib/jump";
import { log } from "console";
import { COOKIE_KEY, PLATFORM, TARGET_URL, TENANT, TENANT_APPID } from "./store";

const Index = () => {
  const layoutRef = useRef<any>();

  /**
   * 请求页面数据
   */
  // 初次加载才显示骨架屏，避免每次下拉页面闪烁
  const [pageFirstLoading, setPageFirstLoading] = useState(false);
  // 用户对应的服务号 openId
  const [tenantOpenId, setTenantOpenId] = useState("");
  // 邀请码： 对应 环境
  const [inviteCode, setInviteCode] = useState("");
  // 是否显示邀请码输入框：如果是扫码则不显示
  const [showInviteCode, setShowInviteCode] = useState(true);

  // 如果监测到  storage 中存在 inviteCode +openId +phoneNumber 则打开小程序时候出现弹窗确认是否进入当前环境
  const [sureInfoModalVisible, setSureInfoModalVisible] = useState(false);

  const [phoneNumber, setPhoneNumber] = useState("");
  const [userInfo, setUserInfo] = useState<any>({});
  const [loginCode, setLoginCode] = useState("");

  const fetchOpenIdList = async () => {
    const res = await getOpenIdList({});
    Log.log("模拟接口调用 res", res);
  };

  const toSetCookie = async (dto: { key: string; value: string }) => {
    const res = await setCookie(dto);
    Log.log("toSetCookie接口调用 res", res);
    return res;
  };
  const toBindUser = async (dto: IBindUserParams) => {
    const res = await bindUser(dto);
    Log.log("toBindUser 接口调用 res", res);
    return res;
  };
  const toDecryptPhoneNumber = async (dto: IDecryptPhoneNumberParams) => {
    const res = await decryptPhoneNumber(dto);
    Log.log("toDecryptPhoneNumber 接口调用 res", res);
    return res;
  };

  const getUserProfile = () => {
    // 推荐使用wx.getUserProfile获取用户信息，开发者每次通过该接口获取用户个人信息均需用户确认
    // 开发者妥善保管用户快速填写的头像昵称，避免重复弹窗
    Taro.getUserProfile({
      desc: "用于完善会员资料", // 声明获取用户个人信息后的用途，后续会展示在弹窗中，请谨慎填写
      success: (res) => {
        console.log("success res", res);

        if (res.errMsg === "getUserProfile:ok") {
          setUserInfo(res.userInfo);
        } else {
        }
      },
      complete: (res) => {
        console.log("complete res", res);
        if (res.errMsg === "getUserProfile:fail auth deny") {
        }
      },
    });
  };

  const onLogin = async (params: any) => {
    const { encryptedData, iv, code } = params;
    const pDto = {
      encryptedData: encryptedData,
      iv: iv,
      code: code,
    };
    Taro.showLoading({
      title: "加载中",
    });
    const decryptRes = await toDecryptPhoneNumber(pDto);
    const { phoneNumber } = decryptRes;
    if (phoneNumber) {
      // 解密成功 去登录
      const dto = {
        tenant: TENANT,
        tenantAppId: TENANT_APPID,
        // tenantOpenId: "oFOzO6F94F08XOI7s3mXWilYdEKU", // 这个从 url获取
        tenantOpenId: tenantOpenId, // 这个从 url获取
        inviteCode: inviteCode,
        phoneNumber: phoneNumber,
      };
      const bindRes = await toBindUser(dto);
      const { content = {} } = bindRes || {};
      const { _id = "", tenantOpenId: _tenantOpenId = "" } = content || {};
      if (_id) {
        // 写入 storage
        Taro.setStorage({
          key: "inviteCode",
          data: inviteCode,
        });
        Taro.setStorage({
          key: "openId",
          data: _tenantOpenId,
        });
        Taro.setStorage({
          key: "phoneNumber",
          data: phoneNumber,
        });
        setTimeout(() =>
          // 绑定成功--》跳转页面
          jump({
            url: `${TARGET_URL}?${COOKIE_KEY}=${inviteCode}&phoneNumber=${phoneNumber}&inviteCode=${inviteCode}&openId=${_tenantOpenId}&platform=${PLATFORM}&timestamp=${new Date().getTime()}`,
            title: "supTPT",
            webviewOpen: true,
            method: "reLaunch",
          })
        );
      } else {
        Taro.showToast({
          title: "用户绑定失败",
          icon: "none",
          duration: 2000,
        });
      }
      Taro.hideLoading();
    } else {
      Taro.hideLoading();
      Taro.showToast({
        title: "手机号获取失败",
        icon: "none",
        duration: 2000,
      });
    }
  };

  /**
   * 授权手机号
   */
  const onGetPhoneNumber = async (e) => {
    Log.log("小程序手机号授权", e);
    Log.log("邀请码inviteCode", inviteCode);

    if (e.detail.errMsg === "getPhoneNumber:ok") {
      const { encryptedData, iv } = e.detail;
      Taro.checkSession({
        success: async () => {
          // 登录状态有效
          console.log("登录态没过期");
          onLogin({
            encryptedData,
            iv,
            code: loginCode,
          });
        },
        fail: () => {
          console.log("登录态过期");
          wxLogin(true).then((code) => {
            setLoginCode(code);
            onLogin({
              encryptedData,
              iv,
              code: code,
            });
          });
        },
      });
    } else {
      Taro.showToast({
        title: "请选择手机号",
        icon: "none",
        duration: 2000,
      });
    }

    // return;
  };

  /**
   * 取消自动登录
   */
  const handleCancel = () => {
    // 1.展示邀请码输入框
    setShowInviteCode(true);
    // 2.关闭弹窗
    setSureInfoModalVisible(false);
  };

  const handleLogin = () => {
    setSureInfoModalVisible(false);

    jump({
      url: `${TARGET_URL}?${COOKIE_KEY}=${inviteCode}&phoneNumber=${phoneNumber}&inviteCode=${inviteCode}&openId=${tenantOpenId}&platform=${PLATFORM}&timestamp=${new Date().getTime()}`,
      title: "supTPT",
      webviewOpen: true,
      method: "reLaunch",
    });
  };

  const wxLogin = (loading = false) => {
    console.log("wxLogin");
    return new Promise((resolve, reject) => {
      if (loading) {
        Taro.showLoading({
          title: "加载中",
        });
      }
      Taro.login({
        success: (res) => {
          console.log("wxLogin success", res);

          Taro.hideLoading();

          const code = res.code;
          resolve(code);
        },
        fail: (res) => {
          console.log("wxLogin fail", res);

          Taro.hideLoading();
          resolve("");
        },
      });
    });
  };

  useLoad(() => {
    wxLogin().then((res: string) => {
      console.log("useLoad code", res);
      setLoginCode(res);
    });

    const { router } = getCurrentInstance();
    const { params } = router || {};
    const { inviteCode = "", openId = "" } = params || {};
    console.log('useLoad params', params);

    if (inviteCode && openId) {
      // 如果是扫码的情况 则不展示 邀请码
      setShowInviteCode(false);
      // 回填表单
      setInviteCode(inviteCode);
      setTenantOpenId(openId);
    } else {
      const inviteCode = Taro.getStorageSync("inviteCode");
      const openId = Taro.getStorageSync("openId");
      const phoneNumber = Taro.getStorageSync("phoneNumber");
      if (inviteCode) {
        // 有缓存邀请码也不展示
        setShowInviteCode(false);
        setInviteCode(inviteCode);
      }
      if (openId) {
        setTenantOpenId(openId);
      }
      if (phoneNumber) {
        setPhoneNumber(phoneNumber);
      }
      console.log("从 storage 获取 inviteCode", inviteCode);
      console.log("从 storage 获取 openId", openId);
      console.log("从 storage 获取 phoneNumber", phoneNumber);
      if (inviteCode && openId && phoneNumber) {
        setSureInfoModalVisible(true);
      }
    }
  });

  return (
    <Layout
      ref={layoutRef}
      // noheader
      loading={pageFirstLoading}
      loadingSlot={<Skeleton />}
      disableDict
    >
      <View className="flex items-center justify-center my-[180rpx]">
        <Image
          src={require("@/assets/img/logo/tpt.png")}
          className="w-[100rpx] h-[100rpx]"
        />
        <View className="ml-1 flex flex-col">
          <Text className="text-[36rpx] leading-none font-medium">
            <Text className="text-[#446ea3]">TPT</Text>
            <Text className="text-[#bd6f3e]">移动端</Text>
          </Text>
          <Text className="text-[24rpx] text-[#aaa] leading-none mt-1">
            SUPCON
          </Text>
        </View>
      </View>
      <View className="mt-0 mx-[50rpx]">
        {showInviteCode && (
          <View className="my-[50rpx]">
            <Input
              type="text"
              placeholder="请输入邀请码"
              value={inviteCode}
              onChange={(e) => {
                setInviteCode(e.target.value);
              }}
              className="w-[600rpx] px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-indigo-500 focus:border-indigo-500"
            />
          </View>
        )}

        <View className="h-[96rpx] relative">
          <Button block type="success" size="large" disabled={!inviteCode}>
            手机号快捷登录
          </Button>
          <button
            disabled={!inviteCode}
            onClick={() => {
              Taro.showLoading({
                title: "加载中",
                duration: 0,
              });
            }}
            open-type="getPhoneNumber"
            onGetPhoneNumber={onGetPhoneNumber}
            className="opacity-0 absolute left-0 top-0 right-0 bottom-0 z-10"
          />
        </View>
      </View>

      <Dialog
        title="检测到存在账户,确认是否登录"
        visible={sureInfoModalVisible}
        footerDirection="vertical"
        confirmText="登录"
        cancelText="取消"
        onConfirm={() => handleLogin()}
        onCancel={() => handleCancel()}
      >
        <View>
          <View className="flex items-center justify-center my-[20rpx]">
            <View className="mr-[10rpx]">邀请码:</View>
            <View>{inviteCode}</View>
          </View>
          <View className="flex items-center justify-center">
            <View className="mr-[10rpx]">手机号:</View>
            <View>{phoneNumber}</View>
          </View>
        </View>
      </Dialog>
      {/* <View className="mt-6 mx-[50rpx] mb-[28rpx]">
        <View className="h-[96rpx] relative">
          <Button
            block
            size="large"
            // onClick={() => {
            //   const backurl = getSearchParams("backurl");
            //   const isSwitchTab = getSearchParams("isSwitchTab");
            //   navigateTo({
            //     url:
            //       "/sub_common/pages/auth/login/index" +
            //       `?backurl=${backurl}&isSwitchTab=${isSwitchTab}`,
            //   });
            // }}
          >
            手机号登录
          </Button>
        </View>
      </View>*/}
    </Layout>
  );
};

export default Index;
